package com.dianrui.moonfire.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.util.CountDownTimerUtils;
import com.dianrui.moonfire.util.GlideUtil;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.ResizableImageView;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Description:引导页
 * User: luoziyin
 * Date: 2020-8-17
 */
public class LoadActivity extends Activity {
    private List<String> imgIdArray = new ArrayList<>();
    private List<String> titlesArray = new ArrayList<>();
    private List<String> urlArray = new ArrayList<>();
    private int currentPosition = 0;
    Context context = this;
    private boolean isStop = false;// 线程标志
    boolean adviseFlag = true;
    private CountDownTimerUtils countDownTimer;
    private ImageView[] imageViews;
    private ImageView imageView;
    private boolean isAuto = true;
    private Timer timer;
    private LoadPageAdapter loadPageAdapter;

    @BindView(R.id.guidePagers)
    ViewPager guildPager;
    @BindView(R.id.tv_skip)
    TextView tvJumps;
    @BindView(R.id.viewGroup)
    ViewGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);
        ButterKnife.bind(this);
        hidebottomuimenu();
        initPic();
        //点击跳转到主界面
        tvJumps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                JumpKillActivitys(MainActivity.class);
                cancelTask();
            }
        });
    }


    boolean isFinishByUser = false;

    @OnClick(R.id.tv_skip)
    public void onViewClicked() {
        isFinishByUser = true;
        JumpKillActivitys(MainActivity.class);
        //startMain();
    }

    private void initPic() {
        if (imgIdArray != null && imgIdArray.size()>0) {
            imgIdArray.clear();
        }
        if (titlesArray != null && titlesArray.size()>0) {
            titlesArray.clear();
        }
        if (urlArray != null && urlArray.size()>0) {
            urlArray.clear();
        }
        JsonObject start = new JsonObject();
        start.addProperty("type", "1");
        XHttpRequest.getInstance().postNormalRequests(Url.ADV, start.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    group.setVisibility(View.VISIBLE);
                                    tvJumps.setVisibility(View.VISIBLE);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject content = new JSONObject(jsonArray.opt(i).toString());
                                        imgIdArray.add(content.optString("picture"));
                                        titlesArray.add(content.optString("title"));
                                        urlArray.add(content.optString("link_url"));
                                    }
                                    if (loadPageAdapter == null) {
                                        loadPageAdapter = new LoadPageAdapter();
                                        guildPager.setAdapter(loadPageAdapter);
                                    } else {
                                        loadPageAdapter.notifyDataSetChanged();
                                    }
                                    guildPager.addOnPageChangeListener(new BannerListener());
                                    if (imgIdArray.size() == 1) {
                                        group.setVisibility(View.GONE);
                                    } else {
                                        initPointer();
                                        group.setVisibility(View.VISIBLE);
                                    }
                                    init((jsonObject.optLong("run_time") + 1) * 1000);

                                    setViewPagerTime();

                                }

                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                tvJumps.setVisibility(View.GONE);
                                group.setVisibility(View.GONE);
                                Intent intent = new Intent(LoadActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                                cancelTask();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
                group.setVisibility(View.GONE);
                tvJumps.setVisibility(View.GONE);
                Intent intent = new Intent(LoadActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void init(long time) {
        countDownTimer = new CountDownTimerUtils(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvJumps.setText(millisUntilFinished / 1000 + " " + "跳过");
                int currentTime = (int) (millisUntilFinished / 1000);
                if (currentTime < 1) {
                    tvJumps.setVisibility(View.GONE);//如果倒计时是0则隐藏
                }

            }

            @Override
            public void onFinish() {
                JumpKillActivitys(MainActivity.class);
                isFinishByUser = true;
                cancelTask();

            }
        };
        countDownTimer.start();
    }


    private void setViewPagerTime() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                guildPager.setCurrentItem(guildPager.getCurrentItem() + 1);
            }
        };
        timer.schedule(task, 0, 2000);
    }


    @Override
    protected void onRestart() {
        if (countDownTimer != null) {
            countDownTimer.onContinue();
        }
        hidebottomuimenu();
        super.onRestart();
    }


    protected void hidebottomuimenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    private void initPointer() {
        //有多少个界面就new多长的数组
        imageViews = new ImageView[imgIdArray.size()];
        for (int i = 0; i < imageViews.length; i++) {
            //new新的ImageView控件
            imageView = new ImageView(this);
            //设置控件的宽高
            imageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
            //设置控件的padding属性
            imageView.setPadding(5, 0, 5, 0);
            imageViews[i] = imageView;
            //初始化第一个page页面的图片的原点为选中状态
            if (i == 0) {
                //表示当前图片
                imageViews[i].setBackgroundResource(R.drawable.green_dot);
            } else {
                imageViews[i].setBackgroundResource(R.drawable.gray_dot);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 10;
            layoutParams.bottomMargin = 15;
            layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
            // 将imageviews添加到小圆点视图组
            group.addView(imageViews[i], layoutParams);
        }
    }

    class LoadPageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (imgIdArray == null) {
                return 0;
            }
            return imgIdArray.size();//图片有多少张就有多少
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ResizableImageView imageView = new ResizableImageView(LoadActivity.this);//直接创建个Imgaeview
            if (imgIdArray != null && imgIdArray.size() > 0) {
                position %= imgIdArray.size();
                GlideUtil.loadImageView(context, imgIdArray.get(position), imageView);
                final int finalPosition = position;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adviseFlag = false;
                        if (countDownTimer != null) {
                            countDownTimer.onPause();
                        }
                        if (!StringUtils.isEmpty(urlArray.get(finalPosition))) {
                            startActivityForResult(new Intent(LoadActivity.this, LoadWebViewActivity.class).putExtra("type", "ad")
                                    .putExtra("titles", titlesArray.get(finalPosition))
                                    .putExtra("url", urlArray.get(finalPosition)), 101);
                        }
                    }
                });
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    class BannerListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[position].setBackgroundResource(R.drawable.green_dot);
                if (position != i) {
                    imageViews[i].setBackgroundResource(R.drawable.gray_dot);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，
                    if (guildPager.getCurrentItem() == guildPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        Intent intent = new Intent(LoadActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (guildPager.getCurrentItem() == 0 && !isAutoPlay) {
                        guildPager.setCurrentItem(guildPager.getAdapter().getCount() - 1);
                    }

                    break;

                default:
                    break;
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            adviseFlag = true;
            startMain();
        }
    }

    private void startMain() {
        if (isFinishByUser && adviseFlag) {
            JumpKillActivitys(MainActivity.class);
            adviseFlag = false;
        }
    }


    protected void JumpActivitys(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    protected void JumpKillActivitys(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        finish();
    }

    public void cancelTask() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (guildPager != null) {
            guildPager.removeOnPageChangeListener(null);
            guildPager.removeAllViews();
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        isAuto = false;
        cancelTask();
    }
}
